/*
 * @Author: cuixuliang
 * @Email: zhangxiao0125@163.com
 * @Date: 2020-06-09 13:24:27
 * @Last Modified by: cuixuliang
 * @Last Modified time: 2020-06-17 15:37:11
 * @Description: 资源中心
 */

import 'package:flutter/material.dart';
import 'package:flutter_code_framework/base/base_widget.dart';
import 'package:flutter_code_framework/model_data/book/book.dart';
import 'package:flutter_code_framework/route/route_transition.dart';

import 'package:flutter_code_framework/utils/global.dart';

import 'package:flutter_code_framework/widgets/x_video_player.dart';
import 'package:flutter_sfsymbols/flutter_sfsymbols.dart';

import 'package:flutter_code_framework/model_data/resource/resourceList.dart';
import 'package:flutter_code_framework/model_data/resource/listviewModel.dart';
import 'package:flutter_code_framework/model_data/resource/resource.dart';

import 'package:flutter_code_framework/pages/lesson/book_list_pop_page.dart';

import 'package:shared_preferences/shared_preferences.dart';

import 'package:flutter/cupertino.dart';

import 'package:flutter_code_framework/model_data/bookmenu/bookmenu.dart';
import 'package:flutter_code_framework/pages/common/select_book_menu.dart';

import 'common/resources_webview.dart';
import 'common/search.dart';
import 'common/voice_player.dart';
import 'package:flutter_code_framework/widgets/video_player.dart';

class ResourcesPage extends BaseWidget {
  String resourceType;

  ResourcesPage({Key key, this.resourceType}) : super(key: key);

  @override
  BaseWidgetState<BaseWidget> getState() {
    return _ResourcesPageState();
  }
}

class _ResourcesPageState extends BaseWidgetState<ResourcesPage> {
  ScrollController _controller = new ScrollController();
  GlobalKey<FormState> _key = GlobalKey<FormState>(); //Form
  TextEditingController _title = TextEditingController();

  ResourceList _items = new ResourceList();
  List<ResourceData> list = [];
  int _pageCount = 1; //总页码
  String _emptyWidgetContent = '';


  String selBookId = ''; //教材ID
  String selBookName = '请选择教材'; //教材名称

  String selPeriodId = ''; //学段ID
  String selSubjectId = ''; //科目ID

  @override
  Widget buildWidget(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Container(
          height: 70,
          margin: EdgeInsets.only(left: 24),
          child: IntrinsicHeight(
            child: Row(children: <Widget>[
              Row(crossAxisAlignment: CrossAxisAlignment.end, children: <Widget>[
                Container(
                  height: 30,
                  //color: Colors.red,
                  //padding: EdgeInsets.only(bottom:0),
                  child: Text(
                    '资源',
                    style: TextStyle(
                      color: Theme.of(context).primaryTextTheme.caption.color,
                      fontSize: 22.0,
                      height: 1.1,
                    ),
                    //overflow:TextOverflow.visible ,
                  ),
                  alignment: Alignment.bottomLeft,
                ),
                Container(
                  height: 30,
                  //color: Colors.red,
                  margin: EdgeInsets.only(left: 5, bottom: 2),
                  child: Text('|',
                      //textAlign:TextAlign.end,
                      style: TextStyle(
                          color: Theme.of(context)
                              .primaryTextTheme
                              .caption
                              .color
                              .withOpacity(0.5),
                          fontSize: 13.0,
                          height: 1.1)),
                  alignment: Alignment.bottomLeft,
                ),
                Container(
                  height: 30,
                  //color: Colors.red,
                  margin: EdgeInsets.only(left: 5, bottom: 2),
                  child: Text('Resources',
                      //textAlign:TextAlign.end,
                      style: TextStyle(
                        color: Theme.of(context).cursorColor,
                        fontSize: 12.0,
                        height: 1.1,
                      )),
                  alignment: Alignment.bottomLeft,
                ),
              ]),
              Expanded(
                child: Container(
                  margin: EdgeInsets.only(right: 15),
                  child: IconButton(
                    icon: Icon(
                      SFSymbols.search,
                      size: 24,
                      color: Theme.of(context).primaryTextTheme.caption.color
                      //Color.fromRGBO(118,118,118,1)
                      ,
                    ),
                    onPressed: () {
                      //跳转搜索页
                      RouteTransition(new Search(resourceType: '资源'))
                          .pushReplacementRoute(context);
                    },
                    //padding : const EdgeInsets.all(8.0),
                    alignment: Alignment.centerRight,
                  ),
                ),
              ),
            ]),
          ),
        ),
        Container(
          height: 50,
          color: Color.fromRGBO(216, 216, 216, 0.5),
          margin: EdgeInsets.only(left: 0.0, top: 0),
          child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                Expanded(
                  flex: 10,
                  child: Padding(
                    padding: EdgeInsets.only(left: 24.0),
                    child: GestureDetector(
                      child: Text(
                        //"魂牵梦萦魂牵梦萦魂牵梦萦魂牵梦萦魂牵梦萦",
                        "${"selBookName".length > 16 ? selBookName.substring(0, 15) + "..." : selBookName}",
                        style: TextStyle(
                            color: Theme.of(context).primaryColor, fontSize: 14.0),
                      ),
                      onTap: () => _selectBook(),
                    ),
                  ),
                ),
                Container(
                  padding: EdgeInsets.only(right: 24),
                  child: Row(
                    children: <Widget>[
                      Container(
                        alignment: Alignment.centerRight,
                        //padding: EdgeInsets.only(right: 20.0),
                        child: GestureDetector(
                          child: Text(
                            "选择章节",
                            style: TextStyle(
                                color: Theme.of(context).primaryColor,
                                fontSize: 14),
                          ),
                          onTap: () => _selectMenu(),
                        ),
                      ),
                      SizedBox(
                        width: 4,
                      ),
                      Icon(
                        SFSymbols.menu,
                        size: 16,
                        color: Theme.of(context).primaryColor,
                      )
                    ],
                  ),
                )
              ]),
        ),
        Expanded(
          child: list.length == 0
              ? Container(child: getEmptyWidget(), alignment: Alignment.center)
              : RefreshIndicator(
                  child: ListView.builder(
                    controller: _controller,
                    physics: BouncingScrollPhysics(),
                    itemCount: list.length + 1,
                    scrollDirection: Axis.vertical,
                    itemBuilder: (BuildContext context, int index) {
                      if (index < list.length) {
                        listviewModel _model = _bindLevelTitle(list[index]);
                        //列表标题
                        return Container(
                            height: 100,
                            child: Column(
                              children: <Widget>[
                                Expanded(
                                    child: InkWell(
                                  child: Padding(
                                      padding: EdgeInsets.fromLTRB(0, 0, 0, 0),
                                      child: Row(
                                        children: <Widget>[
                                          Expanded(
                                            child: Column(
                                              children: <Widget>[
                                                Expanded(
                                                  child: Row(
                                                    children: <Widget>[
                                                      Flexible(
                                                        child: Container(
                                                          margin:
                                                              EdgeInsets.only(
                                                                  left: 24.0,
                                                                  top: 10),
                                                          child:
                                                              // child: //Expanded(
                                                              Text(
                                                                  '${list != null ? list[index].resourcesName : ""}',
                                                                  maxLines: 1,
                                                                  overflow:
                                                                      TextOverflow
                                                                          .ellipsis,
                                                                  style: TextStyle(
                                                                      fontSize:
                                                                          18.0,
                                                                      color: Theme.of(
                                                                              context)
                                                                          .primaryTextTheme
                                                                          .caption
                                                                          .color)),
//                                      onTap: () {
//                                        _resourcePlay(list[index]);
//                                      },
                                                          //),
                                                        ),
                                                      ),
                                                      Container(
                                                        margin: EdgeInsets.only(
                                                            left: 6.0, top: 10),
                                                        child: list != null
                                                            ? Icon(
                                                                _model.icoData,
                                                                size: 21,
                                                                color: Color
                                                                    .fromRGBO(
                                                                        57,
                                                                        135,
                                                                        110,
                                                                        1))
                                                            : null,
                                                      )
                                                    ],
                                                  ),
                                                ),
                                                Expanded(
                                                  child: Container(
                                                    alignment:
                                                        Alignment.centerLeft,
                                                    padding: EdgeInsets.only(
                                                        left: 24.0, bottom: 20),
                                                    child: Text(
                                                        _model.levelTitle,
                                                        style: TextStyle(
                                                            color: Theme.of(
                                                                    context)
                                                                .primaryTextTheme
                                                                .caption
                                                                .color,
                                                            fontSize: 14.0)),
                                                  ),
                                                ),
                                              ],
                                            ),
                                          ),
                                          Expanded(
                                            child: Container(
                                              alignment: Alignment.centerRight,
                                              padding:
                                                  EdgeInsets.only(right: 24.0),
                                              child: Icon(
                                                SFSymbols.chevron_right,
                                                size: 28,
                                                color: Theme.of(context)
                                                    .primaryTextTheme
                                                    .caption
                                                    .color
                                                //Color.fromRGBO(118,118,118,1)
                                                ,
                                              ),
                                            ),
                                          )
                                        ],
                                      )),
                                  onTap: () => _resourcePlay(list[index]),
                                )),
                                Container(
                                  padding: EdgeInsets.only(left: 24, right: 24),
                                  child: Divider(
                                    height: 2,
                                    color: Theme.of(context)
                                        .primaryTextTheme
                                        .caption
                                        .color
                                    //Color.fromRGBO(118,118,118,1)
                                    ,
                                  ),
                                ),
                              ],
                            ));
                      } else {
                        if (1 < _pageCount) {
                          return Container(
                            padding: EdgeInsets.all(16.0),
                            alignment: Alignment.center,
                            child: SizedBox(
                              width: 24.0,
                              height: 24.0,
                              child: CircularProgressIndicator(
                                strokeWidth: 2.0,
                              ),
                            ),
                          );
                        } else {
                          return Container(
                              alignment: Alignment.center,
                              padding: EdgeInsets.all(16.0),
                              child: Text("----我是有底线的-----",
                                  style: TextStyle(color: Colors.grey)));
                        }
                      }
                    },
                  ),
                  onRefresh: _handleRefresh,
                ),
        )
      ],
    );
  }

  void _selectBook() {
    Navigator.of(context).push(new MaterialPageRoute(
        builder: (ctx) => new BookListPopPage(
            reBookId: selBookId,
            reBookName: selBookName,
            rePeriodId: selPeriodId,
            reSubjectId: selSubjectId,
            callback: selectbookcallback)));
  }

  //调用公共教材选择弹窗回调函数
  GetSelectedBook selectbookcallback(
      String bookId, String bookName, String periodId, String subjectId) {
//    print("回调bookName:" + bookName.toString());
//    print("回调bookId:" + bookId.toString());
//    print("回调periodId:" + periodId.toString());
//    print("回调subjectId:" + subjectId.toString());

    bool updata = isEqual(
        selBookId,
        bookId
            .toString()); //当返回的新bookID与原bookID一致，则返回true，否则，返回false。updata若为true，则不刷新资源列表，否则，刷新资源列表。

    selBookId = bookId.toString();
    selBookName = bookName.toString();
    selPeriodId = periodId.toString();
    selSubjectId = subjectId.toString();

    _saveBookInfo(selBookId, selBookName, selSubjectId, selPeriodId, updata);
  }

  //判断两本书是否向同
  bool isEqual(String bookID1, String bookID2) {
    return bookID1 == bookID2;
  }

  void _saveBookInfo(String bookId, String bookName, String subjectId,
      String periodId, bool updata) async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    preferences.setString('selBookId' + G.user.data.userId, bookId);
    preferences.setString('selBookName' + G.user.data.userId, bookName);
    preferences.setString('selSubjectId' + G.user.data.userId, subjectId);
    preferences.setString('selPeriodId' + G.user.data.userId, periodId);

    sectionId = preferences.get('sectionId' + G.user.data.userId + bookId);

    if (sectionId == null) {
      sectionId = '';
    }

    if (bookName == null || bookName.length == 0) {
      selBookName = "请选择教材";
    }

    if (!updata) {
      _getResources(bookId: selBookId, sectionId: sectionId, bottom: updata);
    }

    //_getResources(bookId: bookId);
  }

  void _selectMenu() {
    if (selBookId != null && selBookId.length != 0) {
      List<int> selectids = [];
      if (sectionId.length != 0) {
        List<String> x = sectionId.split(",");

        selectids = new List(x.length);

        for (int i = 0; i < x.length; i++) {
          selectids[i] = int.parse(x[i]);
        }
      }
      //List<int> selectids = [76, 77];
      showBottomSheetDialog(new SelectBookMenu(
          bookId: selBookId,
          bookName: selBookName,
          selectids: selectids,
          callback: selectmenucallback));
    } else {
      showNormalToast(
        '请选择教材',
      );
    }
  }

  //调用公共章节弹窗回调函数
  GetSelectedBookMenu selectmenucallback(List<BookMenu> selectlist) {
    //print("回调" + selectlist.length.toString());

    String sectionId = "";

    for (int i = 0; i < selectlist.length; i++) {
      if (i < selectlist.length - 1) {
        sectionId = sectionId + (selectlist[i].id).toString() + ",";
      } else {
        sectionId = sectionId + (selectlist[i].id).toString();
      }
    }

    _getUtil(sectionId);
  }

  String sectionId = '';

  void _getUtil(String sectionid) async {
    if (sectionid == null) {
      sectionId = '';
    } else {
      sectionId = sectionid;
    }
    SharedPreferences preferences = await SharedPreferences.getInstance();
    preferences.setString(
        'sectionId' + G.user.data.userId + selBookId, sectionId);

    _getResources(bookId: selBookId, sectionId: sectionid);
  }

  //预加载数据
  @override
  void initState() {
    super.initState();
    if (list.length > 0) {
      list.clear();
    }
    _getBookInfo();

    //监听上拉加载数据
    _controller.addListener(() {
      if (_controller.position.pixels == _controller.position.maxScrollExtent) {
        if (1 < _pageCount) {
          _loadMore();
        }
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

  @override
  void onCreate() {
    setLoadingWidgetVisible(true);
  }

  @override
  void onPause() {}

  @override
  void onResume() {}

  // 下拉刷新方法
  Future<Null> _handleRefresh() async {
    await Future.delayed(Duration(seconds: 1), () {
      var _firstTime = "";
      setState(() {
        //_firstTime='2019/1/10 10:23:30';  //模拟数据
        _getResources(
            bookId: selBookId,
            sectionId: sectionId,
            selecttime: _firstTime,
            bottom: false);
      });
    });
  }

  // 上拉加载
  Future<Null> _loadMore() async {
    var _selectTime = list.first.selectTime;

    var pageIndex = (int.parse(list.last.pageIndex) + 1).toString();

    await Future.delayed(Duration(seconds: 2), () {
      setState(() {
        // _mPage++;
        _getResources(
            bookId: selBookId,
            sectionId: sectionId,
            pageIndex: pageIndex,
            selecttime: _selectTime.toString());
      });
    });
  }

  //班级按钮操作
  _classOperation(ResourceData data) {
//    switch(data.type){
//      case "教学班":
//      case "行政班":
//        if(data.isManageTeacher==1){
//          RouteTransition(XDialogPage(
//            '确定要解散此班级吗',
//            callBack: () {
//              dissolve(data.id);
//            },
//          )).pushTransRoute(context);
//        }else{
//          if(data.isJoinClass==1){
//            RouteTransition(XDialogPage(
//              '确定要退出此班级吗',
//              callBack: () {
//                exit(data.id);
//              },
//            )).pushTransRoute(context);
//          }else{
//            apply(data.id);
//          }
//        }
//        break;
//    }
  }


  void _getBookInfo() async {
    SharedPreferences preferences = await SharedPreferences.getInstance();

    selBookId = preferences.get('selBookId' + G.user.data.userId);
    selBookName = preferences.get('selBookName' + G.user.data.userId);
    selPeriodId = preferences.get('selPeriodId' + G.user.data.userId);
    selSubjectId = preferences.get('selSubjectId' + G.user.data.userId);

    if (selBookId == null) {
//      selBookId = G.user.data.bookId.toString();
//      selBookName = G.user.data.bookName.toString();
      //获取用户所在学段和科目下搜索到的教材列表第一本书为默认教材
      var _book = await G.req.bookData.getBookList(
        schoolId: G.user.data.schoolId.toString(),
        periodId: G.user.data.periodId.toString(),
        subjectId: G.user.data.subjectId.toString(), //G.user.data.subjectId
        gradeId: G.user.data.gradeId.toString(),
      );

      if (_book.data['bookList'].length > 0) {
        List<Object> bookList = [];

        bookList.addAll(
            _book.data["bookList"].map((e) => Book.fromJson(e)).toList());
        Book model = bookList[0];

        selBookId = model.id.toString();
        selBookName = model.name.toString();
      }
    }

    if (selBookName == null || selBookName.length == 0) {
      selBookName = "请选择教材";
    }

    if (selSubjectId == null || selSubjectId.length == 0) {
      selSubjectId = G.user.data.subjectId.toString();
    }

    if (selPeriodId == null || selPeriodId.length == 0) {
      selPeriodId = G.user.data.periodId.toString();
    }

    if (selBookId == null || selBookId.length == 0) {
      selBookId = '';
      selBookName = "请选择教材";
    }

    sectionId = preferences.get('sectionId' + G.user.data.userId + selBookId);

    if (sectionId == null || sectionId.length == 0) {
      sectionId = '';
    }

    _getResources(bookId: selBookId, sectionId: sectionId);
  }

  //搜索，默认是全部类型，
  void _getResources(
      {String bookId = "",
      String sectionId = "",
      String pageIndex = "1",
      String selecttime = '',
      bool bottom = true}) async {
    int _totalCount = 0;

    SharedPreferences preferences = await SharedPreferences.getInstance();
    preferences.setString(
        'sectionId' + G.user.data.userId + selBookId, sectionId);

    //var sid = G.user.data.schoolId;

    if (bookId == null || bookId.length == 0) {
      bookId = "";
      sectionId = "";
    }

    var rs = await G.req.resourceData.getFineResourcesList(
        bookId: bookId,
        sectionId: sectionId,
        type: "教材",
        keyword: "",
        pageIndex: pageIndex,
        pageSize: pageNum.toString(),
        selectTime: selecttime);

    _items = ResourceList.fromJson(rs.data);

    if (_items.resources != null && _items.resources.length != 0) {
      if (_items.resources.length > 0) {
        _totalCount = int.parse(_items.resources[0].total);
      }

      //判断上拉/下拉刷新  false 表示下拉刷新 ，true 表示上拉加载
      if (!bottom) {
        list.clear();
        //下拉数据刷新，不更新总页码数
        list.insertAll(0, _items.resources);
      } else {
        if (_totalCount != list.length) {
          if (list.length == 0) {
            list.addAll(_items.resources);
          } else if (list.length > 0 &&
              (int.parse(list.last.pageIndex) !=
                  int.parse(_items.resources.first.pageIndex))) {
            list.addAll(_items.resources);
          }
        }
      }

      if (_totalCount == list.length) {
        _pageCount = 1;
      } else {
        var mPageCount = (_totalCount + pageNum - 1) / pageNum;
        _pageCount = mPageCount.toInt();
      }
    } else {
      list.clear();
      _pageCount = 1;
      _emptyWidgetContent = '暂无数据~';
    }
    setLoadingWidgetVisible(false);

    setState(() {});
  }

  listviewModel _bindLevelTitle(ResourceData data) {
    listviewModel model = new listviewModel();
    switch (data.resourcesType) {
      case "视频":
        model.levelTitle = "时长：" + "${data.duration}";
        model.icoData = SFSymbols.play_rectangle_fill;
        break;
      case "音频":
        model.levelTitle = "时长：" + "${data.duration}";
        model.icoData = Icons.audiotrack;
        break;
      case "文档":
        model.levelTitle = "文件大小：" + "${data.fileSize}";
        model.icoData = SFSymbols.doc_fill;
        break;
      case "网页":
        model.levelTitle = "在线多媒体页面";
        model.icoData = SFSymbols.compass_fill;
        break;
    }
    return model;
  }

  _resourcePlay(ResourceData data) {
    List<VideoType> listVideoType = new List();
    switch (data.resourcesType) {
      case "视频":
        if (data.resourcesUrlSuper.isNotEmpty) {
          listVideoType.add(VideoType(name: '超清', url: data.resourcesUrlSuper));
        }
        if (data.resourcesUrlHigh.isNotEmpty) {
          listVideoType.add(VideoType(name: '高清', url: data.resourcesUrlHigh));
        }
        if (data.resourcesUrlLow.isNotEmpty) {
          listVideoType.add(VideoType(name: '标清', url: data.resourcesUrlLow));
        }
        RouteTransition(VideoPlayer(path: [
          PlayerInputInstance(title: data.resourcesName, list: listVideoType)
        ], sourceType: 'network'))
            .pushTransRoute(context);

        break;
      case "音频":
        RouteTransition(VoicePlayer(url: data.resourcesUrlLow))
            .pushTransRoute(context);
        break;
      case "文档":
      case "网页":
        RouteTransition(ResourcesWebview(
                resourceUrl: data.resourcesUrlLow, title: data.resourcesName))
            .pushTransRoute(context);
        break;
    }
  }
}
